package leetcode.offer;

import leetcode.common.ListNode;

@SuppressWarnings("all")
public class _21_合并两个有序链表 {

    /**
     * 输入：l1 = [1,2,4], l2 = [1,3,4]
     * 输出：[1,1,2,3,4,4]
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummyHead = new ListNode(0);
        ListNode node = dummyHead;
        while (l1 != null && l2 != null) {
            // 结点逐一比较
            if (l1.val <= l2.val) {
                node.next = l1;
                l1 = l1.next;
            } else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        // 两条链表长度不相同的情况处理
        node.next = l1 == null ? l2 : l1;
        return dummyHead.next;
    }
}
